
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
#include "HeFeng.h"

HeFeng::HeFeng() {
}


String H_array[3] = {"0","0","0"};
String W_array[3] = {"0","0","0"};

void HeFeng::fans(HeFengCurrentData *data, String id) {  //获取粉丝数
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient https;
  String url = "https://api.bilibili.com/x/relation/stat?vmid=" + id;
  Serial.print("[HTTPS] begin...bilibili\n");
  if (https.begin(*client, url)) {  // HTTPS
    // start connection and send HTTP header
    int httpCode = https.GET();
    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = https.getString();
        Serial.println(payload);
        DynamicJsonDocument  jsonBuffer(2048);
        deserializeJson(jsonBuffer, payload);
        JsonObject root = jsonBuffer.as<JsonObject>();

        String follower = root["data"]["follower"];
        data->follower = follower;
      }
    } else {
      Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
      data->follower = "-1";
    }

    https.end();
  } else {
    Serial.printf("[HTTPS] Unable to connect\n");
    data->follower = "-1";
  }
}

void HeFeng::doUpdateCurr(HeFengCurrentData *data, String key, String location) {  //获取天气

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient https;
//  https://api.seniverse.com/v3/weather/now.json?key=Sc84LU_9Y1iIcM6vC&location=yangzhou&language=en&unit=c
//  String url = "https://free-api.heweather.net/s6/weather/now?lang=en&location=" + location + "&key=" + key;
  String url = "https://api.seniverse.com/v3/weather/now.json?key=" + key + "&location=" + location + "&language=en&unit=c";
  Serial.print("[HTTPS] begin...now\n");
  if (https.begin(*client, url)) {  // HTTPS
    // start connection and send HTTP header
    int httpCode = https.GET();
    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = https.getString();
        Serial.println(payload);

        StaticJsonDocument<512> doc;
        DeserializationError error = deserializeJson(doc, payload);
        JsonObject results_0 = doc["results"][0];
        JsonObject results_0_location = results_0["location"];
        const char* results_0_location_id = results_0_location["id"]; // "WTUBM40RTTUB"
        const char* results_0_location_name = results_0_location["name"]; // "Yangzhou"
        const char* results_0_location_country = results_0_location["country"]; // "CN"
        const char* results_0_location_path = results_0_location["path"]; // "Yangzhou,Yangzhou,Jiangsu,China"
        const char* results_0_location_timezone = results_0_location["timezone"]; // "Asia/Shanghai"
        const char* results_0_location_timezone_offset = results_0_location["timezone_offset"]; // "+08:00"
        JsonObject results_0_now = results_0["now"];
        const char* results_0_now_text = results_0_now["text"]; // "Sunny"
        const char* results_0_now_code = results_0_now["code"]; // "0"
        const char* results_0_now_temperature = results_0_now["temperature"]; // "29"
        const char* results_0_last_update = results_0["last_update"]; // "2023-06-08T10:50:00+08:00"

        String tmp = results_0_now["temperature"].as<String>();
        data->tmp = tmp;
        String fl = results_0_now["temperature"].as<String>();
        data->fl = fl;

        String cond_code = results_0_now["code"].as<String>();
        String meteoconIcon = getMeteoconIcon(cond_code);
        String cond_txt = results_0_now["text"].as<String>();
        data->cond_txt = cond_txt;
        data->iconMeteoCon = meteoconIcon;

//        DynamicJsonDocument  jsonBuffer(2048);
//        deserializeJson(jsonBuffer, payload);
//        JsonObject root = jsonBuffer.as<JsonObject>();
//
//        String tmp = root["HeWeather6"][0]["now"]["tmp"];
//        data->tmp = tmp;
//        String fl = root["HeWeather6"][0]["now"]["fl"];
//        data->fl = fl;
//        String hum = root["HeWeather6"][0]["now"]["hum"];
//        data->hum = hum;
//        String wind_sc = root["HeWeather6"][0]["now"]["wind_sc"];
//        data->wind_sc = wind_sc;
//        String cond_code = root["HeWeather6"][0]["now"]["cond_code"];
//        String meteoconIcon = getMeteoconIcon(cond_code);
//        String cond_txt = root["HeWeather6"][0]["now"]["cond_txt"];
//        data->cond_txt = cond_txt;
//        data->iconMeteoCon = meteoconIcon;

      }

      String url_gd = "https://restapi.amap.com/v3/weather/weatherInfo?key=xxx&city=xxx";//此处填写高德天气api密钥以及城市编码
        Serial.println("[HTTP] begin gdmap");
        if(https.begin(*client,url_gd)){
          int httpCode = https.GET();
          if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          Serial.printf("[HTTPS] GET... code: %d\n", httpCode);
            if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
              String payload = https.getString();
              Serial.println(payload);
              DynamicJsonDocument jsonBuffer(512);
              deserializeJson(jsonBuffer,payload);
              JsonObject root = jsonBuffer.as<JsonObject>();
              String hum = root["lives"][0]["humidity"];
              data->hum = hum;
              String wind_sc = root["lives"][0]["windpower"];
              data->wind_sc = wind_sc;
        }}}
    } else {
      Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
      data->tmp = "-1";
      data->fl = "-1";
      data->hum = "-1";
      data->wind_sc = "-1";
      data->cond_txt = "no network";
      data->iconMeteoCon = ")";
    }

    https.end();
  } else {
    Serial.printf("[HTTPS] Unable to connect\n");
    data->tmp = "-1";
    data->fl = "-1";
    data->hum = "-1";
    data->wind_sc = "-1";
    data->cond_txt = "no network";
    data->iconMeteoCon = ")";
  }

}

void HeFeng::doUpdateFore(HeFengForeData *data, String key, String location) {  //获取预报

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient https;
//  https://api.seniverse.com/v3/weather/daily.json?key=Sc84LU_9Y1iIcM6vC&location=yangzhou&language=en&unit=c&start=0&days=3
//  String url = "https://free-api.heweather.net/s6/weather/forecast?lang=en&location=" + location + "&key=" + key;
  String url = "https://api.seniverse.com/v3/weather/daily.json?key=" + key + "&location=" + location + "&language=en&unit=c&start=0&days=3";
  Serial.print("[HTTPS] begin...forecast\n");
  if (https.begin(*client, url)) {  // HTTPS
    // start connection and send HTTP header
    int httpCode = https.GET();
    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = https.getString();
        Serial.println(payload);

        DynamicJsonDocument doc(1536);
        DeserializationError error = deserializeJson(doc, payload);
        JsonObject results_0 = doc["results"][0];
        JsonObject results_0_location = results_0["location"];
        const char* results_0_location_id = results_0_location["id"]; // "WTUBM40RTTUB"
        const char* results_0_location_name = results_0_location["name"]; // "Yangzhou"
        const char* results_0_location_country = results_0_location["country"]; // "CN"
        const char* results_0_location_path = results_0_location["path"]; // "Yangzhou,Yangzhou,Jiangsu,China"
        const char* results_0_location_timezone = results_0_location["timezone"]; // "Asia/Shanghai"
        const char* results_0_location_timezone_offset = results_0_location["timezone_offset"]; // "+08:00"
        int i = 0;
        for (JsonObject results_0_daily_item : results_0["daily"].as<JsonArray>()) {
          const char* results_0_daily_item_date = results_0_daily_item["date"]; // "2023-06-08", "2023-06-09", ...
          const char* results_0_daily_item_text_day = results_0_daily_item["text_day"]; // "Sunny", "Sunny", ...
          const char* results_0_daily_item_code_day = results_0_daily_item["code_day"]; // "0", "0", "14"
          const char* results_0_daily_item_text_night = results_0_daily_item["text_night"]; // "Clear", "Clear", ...
          const char* results_0_daily_item_code_night = results_0_daily_item["code_night"]; // "1", "1", "13"
          const char* results_0_daily_item_high = results_0_daily_item["high"]; // "31", "33", "35"
          const char* results_0_daily_item_low = results_0_daily_item["low"]; // "21", "22", "21"
          const char* results_0_daily_item_rainfall = results_0_daily_item["rainfall"]; // "0.00", "0.00", "1.38"
          const char* results_0_daily_item_precip = results_0_daily_item["precip"]; // "0.00", "0.00", "0.44"
          const char* results_0_daily_item_wind_direction = results_0_daily_item["wind_direction"]; // "SW", "SW", ...
          const char* results_0_daily_item_wind_direction_degree = results_0_daily_item["wind_direction_degree"];
          const char* results_0_daily_item_wind_speed = results_0_daily_item["wind_speed"]; // "8.4", "8.4", "3.0"
          const char* results_0_daily_item_wind_scale = results_0_daily_item["wind_scale"]; // "2", "2", "1"
          const char* results_0_daily_item_humidity = results_0_daily_item["humidity"]; // "59", "57", "61"

          String tmp_min = results_0_daily_item["low"].as<String>();
          data[i].tmp_min = tmp_min;
          String tmp_max = results_0_daily_item["high"].as<String>();
          data[i].tmp_max = tmp_max;
          String datestr = results_0_daily_item["date"];
          data[i].datestr = datestr.substring(5, datestr.length());
          String cond_code = results_0_daily_item["code_night"];
//          String cond_code = "9006";
          String meteoconIcon = getMeteoconIcon(cond_code);
          data[i].iconMeteoCon = meteoconIcon;
          H_array[i] = results_0_daily_item["humidity"].as<String>();
          W_array[i] = results_0_daily_item["wind_scale"].as<String>();
          i++;
        }
        const char* results_0_last_update = results_0["last_update"]; // "2023-06-08T08:00:00+08:00"


        
//        DynamicJsonDocument  jsonBuffer(8192);
//        deserializeJson(jsonBuffer, payload);
//        JsonObject root = jsonBuffer.as<JsonObject>();
//        int i;
//        for (i = 0; i < 3; i++) {
//          String tmp_min = root["HeWeather6"][0]["daily_forecast"][i]["tmp_min"];
//          data[i].tmp_min = tmp_min;
//          String tmp_max = root["HeWeather6"][0]["daily_forecast"][i]["tmp_max"];
//          data[i].tmp_max = tmp_max;
//          String datestr = root["HeWeather6"][0]["daily_forecast"][i]["date"];
//          data[i].datestr = datestr.substring(5, datestr.length());
//          String cond_code = root["HeWeather6"][0]["daily_forecast"][i]["cond_code_d"];
//          String meteoconIcon = getMeteoconIcon(cond_code);
//          data[i].iconMeteoCon = meteoconIcon;
//        }
      }
    } else {
      Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
      int i;
      for (i = 0; i < 3; i++) {
        data[i].tmp_min = "-1";
        data[i].tmp_max = "-1";
        data[i].datestr = "N/A";
        data[i].iconMeteoCon = ")";
      }
    }
    https.end();
  } else {
    Serial.printf("[HTTPS] Unable to connect\n");
    int i;
    for (i = 0; i < 3; i++) {
      data[i].tmp_min = "-1";
      data[i].tmp_max = "-1";
      data[i].datestr = "N/A";
      data[i].iconMeteoCon = ")";
    }
  }

}

String HeFeng::getMeteoconIcon(String cond_code) {  //获取天气图标
  if (cond_code == "0" || cond_code == "1" || cond_code == "2" || cond_code == "3" || cond_code == "38") {//晴天
    return "B";
  }
  if (cond_code == "99") {//未知
    return ")";
  }
  if (cond_code == "9") {//阴天
    return "D";
  }
  if (cond_code == "500") {//薄雾，不显示
    return "E";
  }
  if (cond_code == "27" || cond_code == "26" || cond_code == "28" || cond_code == "29") {//沙尘
    return "F";
  }
  if (cond_code == "37") {//雪
    return "G";
  }
  if (cond_code == "5" || cond_code == "6") {//晴间多云
    return "H";
  }
  if (cond_code == "31") {//霾
    return "L";
  }
  if (cond_code == "30") {//雾
    return "M";
  }
  if (cond_code == "4") {//少云
    return "N";
  }
  if (cond_code == "213") {//打雷
    return "O";
  }
  if (cond_code == "11") {//雷阵雨
    return "P";
  }
  if (cond_code == "13" ) {//小雨
    return "Q";
  }
  if (cond_code == "14" || cond_code == "15" || cond_code == "16" || cond_code == "17" || cond_code == "18") {//大雨
    return "R";
  }
  if (cond_code == "32" || cond_code == "33" || cond_code == "34" || cond_code == "35" || cond_code == "36") {//风
    return "S";
  }
  if (cond_code == "10") {//阵雨
    return "T";
  }
  if (cond_code == "22") {//小雪
    return "U";
  }
  if (cond_code == "21") {//阵雪
    return "V";
  }
  if (cond_code == "23" || cond_code == "24" || cond_code == "25") {//大雪
    return "W";
  }
  if (cond_code == "19" || cond_code == "20" || cond_code == "12") {//雨夹雪
    return "X";
  }
  if (cond_code == "7" || cond_code == "8") {//多云
    return "Y";
  }
  return ")";
}
